package com.haifeng.sbtx.common.util;

import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.Locale;

/**
 * <p>
 *  获取Message
 * </p>
 *
 * @author: Haifeng
 * @date: 2019-11-28
 */
@Component
@AllArgsConstructor
public class MessageUtil {

    private final static Logger LOGGER = LoggerFactory.getLogger(MessageUtil.class);

    private final MessageSource messageSource;


    /**
     * 获取Message
     * @param code
     * @return
     */
    public String getMessage(Integer code) {
        String message = "";
        try {
            Locale locale = Locale.getDefault();
            message = messageSource.getMessage(code.toString(), null, locale);
        } catch (Exception e) {
            LOGGER.error("parse message error! ", e);
        }
        return message;
    }

    /**
     * 获取Message
     * @param code
     * @param params
     * @return
     */
    public String getMessage(Integer code, Object[] params) {
        String message = "";
        try {
            Locale locale = LocaleContextHolder.getLocale();
            message = messageSource.getMessage(code.toString(), params, locale);
        } catch (Exception e) {
            LOGGER.error("parse message error! ", e);
        }
        return message;
    }
}
